n,m = map(int,input().split())
mat = []
for i in range(n):
mat.append(list(map(int,input().split())))
d={}
for i in range(n):
for j in range(m):
if mat[i][j] not in d:
d[mat[i][j]] = [[i+1,j+1]]
else:
d[mat[i][j]].append([i+1,j+1])
sumx=[0]*(len(d))
sumy=[0]*(len(d))
for num,i in enumerate(d):
for j in d[i]:
sumx[num]+=j[0]
sumy[num]+=j[1]
ans=0
for i,ele in enumerate(d):
c = len(d[ele])
d[ele].sort()
for curr,ind in enumerate(d[ele]):
if curr>=c-1:
break
ans +=abs(sumx[i]-ind[0] - (c-curr-1)*ind[0])
sumx[i]-=ind[0]
for i,ele in enumerate(d):
c = len(d[ele])
d[ele].sort(key=lambda x:-x[1])
for curr,ind in enumerate(d[ele]):
if curr>=c-1:
break
ans +=abs(sumy[i]-ind[1] - (c-curr-1)*ind[1])
sumy[i]-=ind[1]
print(ans)
/*+Rainybunny+*/
#include <bits/stdc++.h>
#define rep(i, l, r) for (int i = l, rep##i = r; i <= rep##i; ++i)
#define per(i, r, l) for (int i = r, per##i = l; i >= per##i; --i)
typedef long long LL;
typedef std::pair<int, int> PII;
#define fi first
#define se second
inline char fgc() {
static char buf[1 << 17], *p = buf, *q = buf;
return p == q && (q = buf + fread(p = buf, 1, 1 << 17, stdin), p == q) ?
EOF : *p++;
}
template <typename Tp = int>
inline Tp rint() {
Tp x = 0, s = fgc(), f = 1;
for (; s < '0' || '9' < s; s = fgc()) f = s == '-' ? -f : f;
for (; '0' <= s && s <= '9'; s = fgc()) x = x * 10 + (s ^ '0');
return x * f;
}
template <typename Tp>
inline void wint(Tp x) {
if (x < 0) putchar('-'), x = -x;
if (9 < x) wint(x / 10);
putchar(x % 10 ^ '0');
}
const int MAXC = 1e5;
int n, m;
std::vector<std::vector<int> > c;
std::vector<PII> buc[MAXC + 5];
inline LL calc(const int u) {
if (buc[u].empty()) return 0;
std::sort(buc[u].begin(), buc[u].end());
int s = buc[u].size();
LL ret = 0, pre = 0;
rep (i, 0, s - 1) {
ret += 1ll * buc[u][i].fi * i - pre, pre += buc[u][i].fi;
}
std::sort(buc[u].begin(), buc[u].end(),
[](const PII& x, const PII& y) { return x.se < y.se; });
pre = 0;
rep (i, 0, s - 1) {
ret += 1ll * buc[u][i].se * i - pre, pre += buc[u][i].se;
}
return ret;
}
int main() {
n = rint(), m = rint();
rep (i, 1, n) rep (j, 1, m) buc[rint()].push_back({ i, j });
LL ans = 0;
rep (i, 1, MAXC) ans += calc(i);
wint(ans), putchar('\n');
return 0;
}
1506A - Strange Table | 456A - Laptops |
855B - Marvolo Gaunt's Ring | 1454A - Special Permutation |
1359A - Berland Poker | 459A - Pashmak and Garden |
1327B - Princesses and Princes | 1450F - The Struggling Contestant |
1399B - Gifts Fixing | 1138A - Sushi for Two |
982C - Cut 'em all | 931A - Friends Meeting |
1594A - Consecutive Sum Riddle | 1466A - Bovine Dilemma |
454A - Little Pony and Crystal Mine | 2A - Winner |
1622B - Berland Music | 1139B - Chocolates |
1371A - Magical Sticks | 1253A - Single Push |
706B - Interesting drink | 1265A - Beautiful String |
214A - System of Equations | 287A - IQ Test |
1108A - Two distinct points | 1064A - Make a triangle |
1245C - Constanze's Machine | 1005A - Tanya and Stairways |
1663F - In Every Generation | 1108B - Divisors of Two Integers |